<template>
  <div class="file-list-wrapper">
    <!-- 操作按钮 -->
    <el-header>
      <OperationMenu
          :operationFile="operationFile"
          :selectionFile="selectionFile"
          :filePath="filePath().current()"
          v-model:batchOperate="batchOperate"
          @getSearchFileList="getSearchFileList"
          @getTableDataByType="getTableDataByType"
          @setMoveFileDialogData="setMoveFileDialogData"
      ></OperationMenu>
    </el-header>    
    <div class="middle-wrapper">
      <!-- 面包屑导航栏 -->      
      <wangpanBreadCrumb class="breadcrumb"></wangpanBreadCrumb>     
    </div>
    <!-- 文件列表-表格模式 -->
    
    <FileTable
        :fileList="fileList"
        :loading="loading"
        @setMoveFileDialogData="setMoveFileDialogData"
        @setOperationFile="setOperationFile"
        @setSelectionFile="setSelectionFile"
        @getTableDataByType="getTableDataByType"
    ></FileTable>
    
    <!-- 文件列表-网格模式 -->
    
    <FileGrid
        :fileList="fileList"
        :loading="loading"
        :batchOperate="batchOperate"
        v-if="fileModel().isGrid()"
        @setMoveFileDialogData="setMoveFileDialogData"
        @setOperationFile="setOperationFile"
        @setSelectionFile="setSelectionFile"
        @getTableDataByType="getTableDataByType"
    ></FileGrid>
    
    <!-- 图片-时间线模式 -->
    
    <FileTimeLine class="image-model" v-if="fileModel().isTimeLine()" :fileList="fileList"></FileTimeLine>
	
    <div class="pagination-wrapper">
      <div class="current-page-count">当前页{{ fileList.length }}条</div>
      <el-pagination
          :current-page="pageData.currentPage"
          :page-size="pageData.pageCount"
          :total="pageData.total"
          :page-sizes="[10, 50, 100, 200]"
          layout="sizes, total, prev, pager, next"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
      >
      </el-pagination>
    </div>
    <!-- 移动文件模态框 -->
    
    <MoveFileDialog
        :dialogMoveFile="dialogMoveFile"
        @setSelectFilePath="setSelectFilePath"
        @confirmMoveFile="confirmMoveFile"
        @setMoveFileDialogData="setMoveFileDialogData"
    ></MoveFileDialog>
   
  </div>
</template>

<script>
import OperationMenu from './components/OperationMenu.vue'
import wangpanBreadCrumb from './components/wangpanBreadCrumb.vue'
import FileTable from './components/FileTable.vue'
import FileGrid from './components/FileGrid.vue'
import FileTimeLine from './components/FileTimeLine.vue'
import MoveFileDialog from './components/MoveFileDialog.vue'

import {
  getFileList,
  selectFileByFileType,
  getRecoveryFile,
  getFileTree,
  moveFile,
  batchMoveFile,
  searchFile,
} from '/@/request/file.js'

import { watch, computed, onMounted, toRefs, reactive, getCurrentInstance } from 'vue';
import { useStore } from '/@/store/index';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { wangpanGlobal }  from '/@/utils/wangpanGlobalConst';
import {isLoginPage,fileModel,fileType,filePath} from '/@/utils/wangpanGlobalFunction';


export default {
	name: 'FileList',
  	components: {
	    OperationMenu,
	    wangpanBreadCrumb,
	    FileTable,
	    FileGrid,
	    FileTimeLine,
	    MoveFileDialog
	  },
	 setup() {
		const store=useStore();
  		const { proxy }=getCurrentInstance();
	 	
	 	const state = reactive({
	      fileNameSearch: '',
	      loading: true, //  表格数据-loading
	      fileList: [], //  表格数据-文件列表
	      pageData: {
	        currentPage: 1,
	        pageCount: 10,
	        total: 0
	      },
	      //  移动文件模态框数据
	      dialogMoveFile: {
	        isBatchMove: false,
	        visible: false, //  是否可见
	        fileTree: [] //  目录树
	      },
	      selectFilePath: Number, //  移动文件路径
	      operationFile: {}, // 当前操作行
	      selectionFile: [], // 勾选的文件
	      batchOperate: false //  批量操作模式
	    });

	    const currentPath = computed(()=>{
        console.log('%c [ proxy.$route ]-135', 'font-size:13px; background:pink; color:#bf2c9f;', proxy.$route)
	    	return proxy.$route.query.pid
	    });
	    const currentFileType = computed(()=>{
	    	return proxy.$route.query.fileType
	    });
		const currentFileModel= computed(()=>{
	      return store.state.wangpanFileList.fileModel
	    });

	    watch (()=>proxy.$route.query.pid,(val)=>{
	    	console.log('watch proxy.$route.query.pid++++');
	    	console.log(val);
	    	
	    	getTableDataByType()
      		setPageCount()
	    });
	    watch (()=>proxy.$route.query.fileType,(val,old)=>{	    	
	    	
	    	console.log('watch proxy.$route.query.fileType++++');
	    	console.log(val,old);
	    	
	    	if (old === wangpanGlobal.gFILE_TYPE.IMAGE && fileModel().isTimeLine()) {
		        store.commit('wangpanFileList/changeFileModel', wangpanGlobal.gFILE_MODEL.TABLE)
		    }
	    	getTableDataByType()
      		setPageCount()
	    });
	    watch (()=>store.state.wangpanFileList.fileModel,(val)=>{
	    	getTableDataByType()
      		setPageCount()
	    });

	    onMounted(() => {
			store.dispatch('wangpanFileList/fetchPathTreeMap')
		    setPageCount()
		    getTableDataByType()
		});
		const reflushFileList = (res)=> {
	      state.loading = false
	      state.fileList = res.data
	      state.pageData.total = res.total
	    };
    // 调整分页大小
    const setPageCount = ()=> {
      state.pageData.currentPage = 1
      if (fileModel().isTable()) {
        state.pageData.pageCount = 10
      }
      if (fileModel().isGrid()) {
        state.pageData.pageCount = 40
      }
    };
    // 获取文件列表数据
    const getTableDataByType = ()=> {
      state.batchOperate = false
      state.loading = true
      // 分类型
      if (fileType().current() && fileType().isNotAll()) {     
        if (fileType().isRecycle()) {        
          showFileRecovery() //  回收站
        } else {
          showFileListByType()
        }
      } else {
        // 全部文件
        showFileList()
      }
    };
    // 获取当前路径下的文件列表
    const showFileList = ()=> {
      let data = {
        currentPage: state.pageData.currentPage,
        pageCount: state.pageData.pageCount
      }
      console.log('%c [ currentPath.value ]-210', 'font-size:13px; background:pink; color:#bf2c9f;', currentPath.value)
      if (currentPath.value != null){
        data.pid = currentPath.value
      }
      getFileList(data).then((res) => {
        reflushFileList(res)
      }).catch(err => {
        console.log(err)
        ElMessage.error("服务器正忙")
      })
    };
    // 分页组件 当前页码改变
    const handleCurrentChange = (currentPage)=> {
      state.pageData.currentPage = currentPage
      state.getTableDataByType()
    };
    const handleSizeChange = (pageCount)=> {
      state.pageData.pageCount = pageCount
      getTableDataByType()
    };
    // 获取回收站文件列表
    const showFileRecovery = ()=> {
      let data = {
        currentPage: state.pageData.currentPage,
        pageCount: state.pageData.pageCount
      }
      getRecoveryFile(data).then((res) => {
        reflushFileList(res)
      }).catch(err =>{
        console.log(err)
        ElMessage.error("服务器正忙")
      })
    };
    // 根据文件类型展示文件列表
    const showFileListByType = ()=> {
      //  分类型
      let data = {
        currentPage: state.pageData.currentPage,
        pageCount: state.pageData.pageCount,
        fileType: fileType().current()
      }
      if (!data.fileType)
      	data.fileType='ALL';
      	
      selectFileByFileType(data).then((res) => {
        reflushFileList(res)
      }).catch(err => {
        console.log(err);
        ElMessage.error("服务器正忙");
      })
    };

    /**
     * 表格勾选框事件
     */
    //  勾选的行
    
    const setSelectionFile = (selection)=> {
      state.selectionFile = selection
    };

    /**
     * 移动按钮相关事件
     */
     //----
    //  当前操作行
    const setOperationFile = (operationFile)=> {
      state.operationFile = operationFile
    };
    //  设置移动文件模态框相关数据，isBatchMove为null时是确认移动，值由之前的值而定
    const setMoveFileDialogData = (isBatchMove, visible)=> {
      initFileTree()
      state.dialogMoveFile.isBatchMove = isBatchMove ? isBatchMove : state.dialogMoveFile.isBatchMove
      state.dialogMoveFile.visible = visible
    };
    //  移动文件模态框：初始化文件目录树
    const initFileTree = ()=> {
      getFileTree().then((res) => {
      	console.log(res)
      	console.log([res])
        state.dialogMoveFile.fileTree = [res]
      }).catch(err => {
        console.log(err)
        ElMessage.error("服务器正忙")
      })
    };
    //  设置移动后的文件路径
    const setSelectFilePath = (selectFilePath)=> {
      state.selectFilePath = selectFilePath
    };
    
    //  移动文件模态框-确定按钮事件
    const confirmMoveFile = ()=> {
      if (state.dialogMoveFile.isBatchMove) {
        //  批量移动
        let data = {
          from: state.selectionFile.flatMap(row => row.id),
          to: state.selectFilePath
        }
        if (!data.to) {
          delete data.to
        }
        batchMoveFile(data).then(() => {
          ElMessage.success("文件移动成功")
          getTableDataByType()
          state.dialogMoveFile.visible = false
          state.selectionFile = []
          store.dispatch('wangpanFileList/fetchPathTreeMap')
        }).catch(err => {
          console.error(err)
          ElMessage.error("系统忙，移动失败")
        })
      } else {
        //  单文件移动
        let data = {
          from: state.operationFile.id,
          to: state.selectFilePath,
        }
        if (!data.to) {
          delete data.to
        }
        moveFile(data).then(() => {
          store.dispatch('wangpanFileList/fetchPathTreeMap')
          ElMessage.success('移动文件成功')
          getTableDataByType()
          state.dialogMoveFile.visible = false
        }).catch(err => {
          console.error(err)
          ElMessage.error("系统忙，移动失败")
        })
      }
    };
    // 获取搜索文件结果列表
    const getSearchFileList = (filename)=> {
      state.loading = true
      searchFile({
        currentPage: state.pageData.currentPage,
        pageCount: state.pageData.pageCount,
        filename: filename
      }).then(res => {
        reflushFileList(res)
      }).catch(err => {
        console.error(err)
        ElMessage.error("服务器正忙")
      })
      };
    return{
    	currentPath,
		currentFileType,
		currentFileModel,
		getTableDataByType,
		setMoveFileDialogData,
		setOperationFile,
		setSelectionFile,
		fileModel,
		handleCurrentChange,
		handleSizeChange,
		setSelectFilePath,
		confirmMoveFile,
		filePath,
		getSearchFileList,
    	...toRefs(state),
    };
	},
}
</script>

<style lang="stylus" scoped>
@import '../styles/varibles.styl'
.file-list-wrapper
  :deep(.el-header)
    padding 0

  .middle-wrapper
    margin-bottom 8px

  .pagination-wrapper
    position relative
    border-top 1px solid $BorderBase
    height 44px
    line-height 44px
    text-align center

    .current-page-count
      position absolute
      left 16px
      height 32px
      line-height 32px
      font-size 13px
      color $RegularText
</style>
